import random
import collections
from LocalStateManager import LocalStateManager

class KQueensStateManager(LocalStateManager):

	numberSuccessors = 20
	kQueensMode = [8, 25, 1000] #mode easy, medium, hard
	
	def __init__(self, k):
		super(KQueensStateManager, self).__init__(k)

	def generateInitState(self):
		self.currentState = []
		for i in range(KQueensStateManager.kQueensMode[self.currentMode]):
			random.seed()
			while True:
				num = random.randint(0, KQueensStateManager.kQueensMode[self.currentMode]-1)
				if num not in self.currentState:
					break
			self.currentState += [num]
		#print "Starting state :"
		#print self.currentState

	#generate successor of the current state
	def generateSuccessors(self):
		random.seed() #init a random generator
		successors = []
		for i in range(KQueensStateManager.numberSuccessors):
			random.seed()
			successor_state = []
			for j in range(len(self.currentState)):
				while True:
					k = random.randint(0, len(self.currentState)-1)
					if k not in successor_state:
						break
				successor_state += [k]
			successors += [successor_state]
		return successors
		
	def modifyState(self, var, value):
		index = self.currentState.index(value)
		temp = self.currentState[index]
		self.currentState[index] = self.currentState[var]
		self.currentState[var] = temp
		
	#evalutate the state (checking costraints violations)
	def evalutateState(self, state):
		violations = 0
		for i in range(len(state)-1):
			if state[i]+1 == state[i+1] or state[i] == state[i+1]+1:
				violations+= 1
		lst = collections.Counter(state).most_common()
		for i in range(len(lst)):
			if lst[i][1] > 1:
				violations+=lst[i][1]-1
		return violations